package codeine.servlets;

import static com.google.common.collect.Maps.newHashMap;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import codeine.NodesManagerServer;
import codeine.jsons.nodes.NodeJson;
import codeine.jsons.project.ProjectJson;
import codeine.jsons.project_status.ProjectStatus;
import codeine.jsons.project_status.ProjectStatusList;
import codeine.model.Constants;
import codeine.utils.StringUtils;
import codeine.version.VersionItem;

import com.google.inject.Inject;


public class NodeAggregator
{
	@Inject private NodesManagerServer nodesManager;
	
	public Map<String, VersionItem> aggregate(Map<String, ProjectStatusList> peer_to_projects, ProjectJson projectJson) {
		Map<String, VersionItem> items = newHashMap();
		VersionItem versionItemAll = newVersionItem(items, Constants.ALL_VERSION);
		for (Entry<String, ProjectStatusList> entry : peer_to_projects.entrySet())
		{
			String peerName = entry.getKey();
			String peerNameNoPort = peerName.contains(":") ? peerName.substring(0, peerName.indexOf(':')) : peerName;
			List<NodeJson> nodes = nodesManager.getNodes(projectJson, peerNameNoPort);
			for (NodeJson nodeJson : nodes) {
				String version = getVersion(entry, projectJson.name(), nodeJson.name());
				VersionItem versionItem = items.get(version);
				if (null == versionItem) {
					versionItem = newVersionItem(items, version);
				}
				versionItem.add(entry.getKey());
				versionItemAll.add(entry.getKey());
			}
		}
		return items;
	}

	private VersionItem newVersionItem(Map<String, VersionItem> items, String version) {
		VersionItem versionItem;
		versionItem = new VersionItem(version);
		items.put(version, versionItem);
		return versionItem;
	}

	private String getVersion(Entry<String, ProjectStatusList> entry, String project, String nodeName) {
		ProjectStatus projectStatus = entry.getValue().project_name_to_status.get(project);
		if (null == projectStatus){
			return Constants.NO_VERSION;
		}
		Map<String, String> map = projectStatus.monitor_to_status().get(nodeName);
		if (null == map){
			return Constants.NO_VERSION;
		}
		String version = map.get("version");
		if (StringUtils.isEmpty(version)){
			return Constants.NO_VERSION;
		}
		return version;
	}

}
